package mx.netbrain.dao.impl;

import java.util.List;

import mx.netbrain.dao.TypeFileDao;
import mx.netbrain.model.Type;
import mx.netbrain.util.HibernateUtil;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;

public class TypeFileDaoImpl implements TypeFileDao {

	private static final Logger logger = Logger
			.getLogger(TypeFileDaoImpl.class);

	@Override
	public void save(Type typeFile) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			session.persist(typeFile);
			session.beginTransaction().commit();
		} catch (Exception e) {
			logger.error("Save: " + e.getMessage());
			session.beginTransaction().rollback();
		}
	}

	@Override
	public void update(Type typeFile) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			session.merge(typeFile);
			session.beginTransaction().commit();
		} catch (Exception e) {
			logger.error("Update: " + e.getMessage());
			session.beginTransaction().rollback();
		}
	}

	@Override
	public Type findById(Long id) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		return (Type) session.load(Type.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Type> listAll() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		return session.createQuery("from Type").list();
	}

	@Override
	public void delete(Type typeFile) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			session.delete(typeFile);
			session.beginTransaction().commit();
		} catch (Exception e) {
			logger.error("Delete: " + e.getMessage());
			session.beginTransaction().rollback();
		}
	}

	@Override
	public Type findByExtension(String ext) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		String sql = "select type from Type as type where type.extension = :ext";
		Query query = session.createQuery(sql);
		query.setString("ext", ext);
		if ((Type) query.uniqueResult() != null) {
			return (Type) query.uniqueResult();
		} else {
			logger.error("No se encontro ningun registro con la extension: "
					+ ext);
			return (Type) query.uniqueResult();
		}
	}

}
